package com.wcj.linktable;

/**
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * 输入：head = [1,2,3,4,5], n = 2
 * 输出：[1,2,3,5]
 */
public class 删除链表的倒数第N个节点 {


    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null){
            return null;
        }
        ListNode tmp = head;
        int count = 1;
        while (tmp.next != null){
            tmp = tmp.next;
            count++;
        }
        if (n > count){
            return null;
        }
        tmp = head;
        if (n != count){
            for (int i = 0; i < count - n -1; i++){
                tmp = tmp.next;
            }
            tmp.next = tmp.next.next;
        }else {
            head = head.next;
        }


        return head;
    }
}
